<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Core\Log;
use App\Exception\AppTokenValidException;
use App\Model\User;
use Hyperf\Utils\Context;
use Phper666\JwtAuth\Exception\TokenValidException;
use Phper666\JwtAuth\Jwt;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Hyperf\Di\Annotation\Inject;
use Psr\Http\Server\RequestHandlerInterface;

class UserJwtAuthMiddleware implements MiddlewareInterface
{
    /**
     * @Inject
     * @var ServerRequestInterface
     */
    protected $request;

    /**
     * @Inject
     * @var Jwt
     */
    protected $jwt;

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $params = $request->getMethod()=='GET'?$request->getQueryParams():$request->getParsedBody();
        try {
            $token = $this->jwt->getTokenObj();
            if ($this->jwt->checkToken()) {
                $userId = $token->getClaim('user_id');
                $user = User::where('union_id', $userId)->first();
                if (!$user) {
                    throw new \Exception('用户不存在',4014);
                }
                $request = $request->withAttribute('user', $user);
                Context::set(ServerRequestInterface::class, $request);
            }else{
                if(redis()->get($params['nonce_str'])){
                    redis()->del($params['nonce_str']);
                }
                throw new \Exception('Token未验证通过',401);
            }
        } catch (\Exception $e) {
            throw new TokenValidException($e->getMessage(), $e->getCode());
        }
        return $handler->handle($request);
    }
}